package cn.ltgodm.template.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.ltgodm.template.common.domain.entity.LoginUser;
import cn.ltgodm.template.common.enums.UserStatusEnum;
import cn.ltgodm.template.common.exception.ServiceException;
import cn.ltgodm.template.common.utils.MessageUtils;
import cn.ltgodm.template.common.domain.vo.UserVO;
import cn.ltgodm.template.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author ltgodm
 * @date 2024-03-17 22:33:45
 * 用户验证处理
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserService userService;
    @Resource
    private PermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserVO user = userService.selectUserByUserName(username);
        if (ObjectUtil.isNull(user)){
            log.info("登录用户：{} 不存在",username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (UserStatusEnum.DELETED.getCode().equals(user.getDelFlag().toString())) {
            log.info("登录用户：{} 已被删除",username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        } else if (UserStatusEnum.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用",username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

        //校验密码
        userService.validate(user);

        return createLoginUser(user);
    }

    /**
     * 创建一个登录的用户
     * @param user 用户信息
     * @return 返回登录用户
     */
    private UserDetails createLoginUser(UserVO user) {
        Set<String> permissions = permissionService.getMenuPermission(user);
        return new LoginUser(user.getUserId(),user.getDeptId(),user,permissions);
    }
}
